package db4oClass.appClass;

import general.appClass.SystemInfo;
import general.dbClass.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.db4o.ObjectContainer;
import db4oClass.daoClass.Db4oDaoGet;
import db4oClass.daoClass.Db4oDaoUpdate;


/**
 * Servlet implementation class UploadApp
 */
@WebServlet("/db4oUpdateApp")
public class db4oUpdateApp extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public db4oUpdateApp() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SystemInfo.init(request);

		response.setContentType("text/html; charset=UTF-8");
		ObjectContainer 	conn = SystemInfo.getDb4oConn(request);

		String action = request.getParameter("action");
		if (action != null && action.equals("uploadImage")) {
			String type = request.getParameter("type");
			if (type != null && type.equals("single")) {
				this.insertSingleImg(conn,request, response);
			} else {
				this.insertMultiImg(conn,request, response);
			}

		}

		if (action != null && action.equals("insertKeyword"))
			this.insertKeyword(conn, request, response);
		if (action != null && action.equals("insertCategory"))
			this.insertCategory(conn, request, response);
		if (action != null && action.equals("modifyCategory")) {
			this.modifyCategory(conn, request, response);
		}
		if (action != null && action.equals("modifyKeyword")) {
			this.modifyKeyword(conn, request, response);
		}
		if (action != null && action.equals("deleteCategory")) {
			this.deleteCategory(conn, request, response);
		}
		if (action != null && action.equals("deleteKeyword")) {
			this.deleteKeyword(conn, request, response);
		}
	}
	
	private void deleteKeyword(ObjectContainer container,HttpServletRequest request, HttpServletResponse response) 
									throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("nr"));
		
		if(Db4oDaoUpdate.deleteKeywordById(container,nr)) {
			String url = response.encodeURL("/db4oSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}else {
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", "keyword's id doesn't exist.");
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private void deleteCategory(ObjectContainer container,HttpServletRequest request, HttpServletResponse response) 
									throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("nr"));
		
		if(Db4oDaoUpdate.deleteCategoryById(container,nr)) {
			String url = response.encodeURL("/db4oSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}else {
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", "keyword's id doesn't exist.");
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private void modifyKeyword(ObjectContainer container,HttpServletRequest request, HttpServletResponse response) 
									throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("nr"));
		String value = request.getParameter("value");
		
		if(Db4oDaoUpdate.changeKeywordNameById(container, value, nr)) {
			String url = response.encodeURL("/db4oSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}else {
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", "keyword's id doesn't exist.");
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	private void modifyCategory(ObjectContainer container,HttpServletRequest request, HttpServletResponse response) 
									throws ServletException, IOException {
		int nr = Integer.parseInt(request.getParameter("nr"));
		String value = request.getParameter("value");
		
		if(Db4oDaoUpdate.changeCategoryNameById(container, value, nr)) {
			String url = response.encodeURL("/db4oSearchApp?searchFor=categories");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}else {
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", "category's id doesn't exist.");
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	/**
	 * insert new Category into db4o database
	 * @param container				object container
	 * @param request				request from browser
	 * @param response				response to browser
	 * @throws ServletException		
	 * @throws IOException
	 */
	private void insertCategory(ObjectContainer container,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("category");
		String url = "";

		if(name == null || name.equals(""))
			return;
		
		if(Db4oDaoUpdate.insertNewCategory(container, name)) {
			request.setAttribute("msg",
								"Insert Category " + 
								name + 
								" successfully");
		
			url = response.encodeURL("/successful.jsp");
		}else {
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error",
								"Category " + name + "exists already.");
			url = response.encodeURL("/errorInfo.jsp");
		}
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	/**
	 * insert new keyword in db4o database
	 * @param container				object container	
	 * @param request				request from browser
	 * @param response				response to browser
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void insertKeyword(ObjectContainer container,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("word");
		String url = "";

		if(name == null || name.equals(""))
			return;
		
		if(Db4oDaoUpdate.insertNewKeyword(container, name)) {
			request.setAttribute("msg",
								"Insert Keyword " + 
								name + 
								" successfully");
		
			url = response.encodeURL("/successful.jsp");
		}else {
			request.setAttribute("Error",
								"Keyword " + name + "exists already.");
			url = response.encodeURL("/errorInfo.jsp");
		}
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	/**
	 * insert several images into db4o database.
	 * @param request			request from browser
	 * @param response			response to browser
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@SuppressWarnings("rawtypes")
	private void insertMultiImg(ObjectContainer container,HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//ArrayList<DBPicInfo> imgList = new ArrayList<DBPicInfo>();
		//ArrayList<FileItem> fileItemList = new ArrayList<FileItem>();
		
		int count=0;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);

			if (!ServletFileUpload.isMultipartContent(request)) {
				//System.out.println("sorry. No file gefound");
				return;
			}
			
			// parse request
			List items = sfu.parseRequest(request);
			FileItem file = null;
			ArrayList<DBCategory> categories = new ArrayList<DBCategory>();
			ArrayList<DBKeyword> keywords = new ArrayList<DBKeyword>();
			Iterator iter = items.iterator();
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();

				if (!item.isFormField()) {
					file = item;
					String fileName = file.getName();
					if (fileName.indexOf(".") > 0) {
						String fileType = fileName.substring(fileName
								.lastIndexOf("."));
						if (fileType.equalsIgnoreCase(".jpg")
								|| fileType.equalsIgnoreCase(".jpeg")) {
							//fileItemList.add(file);
							DBPicInfo image = new DBPicInfo();
							image.setName(fileName);
							image.setRate(3);
							image.setCategories(categories);
							image.setKeywords(keywords);
							//imgList.add(image);
							
							byte[] data = item.get();
							image.setExif(data);
							
							Db4oDaoUpdate.insertNewPhoto(container,image,data);
							count++;
						}
					}

				}
			}
			
			if (count==0){
				String url = response.encodeURL("/errorInfo.jsp");
				request.setAttribute("Error", "Kein Photo ist hohegeladen!");
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher(url);
				dispatcher.forward(request, response);	
			}else{
				String url = response.encodeURL("/successful.jsp");
				RequestDispatcher dispatcher = getServletContext()
						.getRequestDispatcher(url);
				dispatcher.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}

	/**
	 * insert single image into db4o database
	 * @param request			request from browser
	 * @param response			response to browser
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@SuppressWarnings("rawtypes")
	private void insertSingleImg(ObjectContainer container,HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		DBPicInfo image = new DBPicInfo();

		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);

			if (!ServletFileUpload.isMultipartContent(request)) {
				//System.out.println("sorry. No file gefound");
				return;
			}
			
			// parse request
			List items = sfu.parseRequest(request);
			FileItem file = null;
			ArrayList<DBCategory> categories = new ArrayList<DBCategory>();
			ArrayList<DBKeyword> keywords = new ArrayList<DBKeyword>();

			Iterator iter = items.iterator();

			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();

				if (item.isFormField()) {
					if (item.getFieldName().equals("imgName")) {
						if (item.getString().equals("")) {
							image.setName(file.getName());
						} else {
							image.setName(item.getString());
						}

					}

					if (item.getFieldName().equals("imgRate")) {
						if (item.getString().equals("")) {
							image.setRate(3);
						} else {
							image.setRate(Integer.parseInt(item.getString()));
						}

					}

					if (item.getFieldName().equals("categorie")) {
						int nr = Integer.parseInt(item.getString());
						DBCategory tmp = Db4oDaoGet.getCategoryById(container, nr);
						
						categories.add(tmp);
					}

					if (item.getFieldName().equals("keywords")) {
						String keywordsInput = item.getString();
						String delims = ",";
						String[] tmp = keywordsInput.split(delims);
						for (int i = 0; i < tmp.length; i++) {
							if (tmp[i].equals(""))
								break;
							int nr = Integer.parseInt(tmp[i]);
							DBKeyword keyword = Db4oDaoGet.getTagById(container, nr);
							keywords.add(keyword);
						}
					}
				} else {
					file = item;
				}
			}

			image.setCategories(categories);
			image.setKeywords(keywords);

			byte[] data = file.get();
			image.setExif(data);
			
			Db4oDaoUpdate.insertNewPhoto(container,image,data);
			request.setAttribute("msg", "Insert Picture successfully!");
			String url = response.encodeURL("/successful.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		} catch (Exception ex) {
			ex.printStackTrace();
			String message = ex.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext()
					.getRequestDispatcher(url);
			dispatcher.forward(request, response);
		}
	}
}
